In [2]:
import numpy as np
import pandas as pd
from IPython.display import Image

Predictive Modeling

What we saw above is a common setup. We have $\mathbf{X}$ and $\mathbf{y}$ data from the past and $\mathbf{X}$ data for the present for which we want to predict the future $\mathbf{y}$ values.

We can generalize this notion of past / present data into what's generally called train and test data.

  • Training Data -- A dataset that we use to train our model. We have both $\mathbf{X}$ and $\mathbf{y}$
  • Testing Data -- A dataset which only has $\mathbf{X}$ values and for which we need to predict $\mathbf{y}$ values. We might also have access to the real $\mathbf{y}$ values so that we can test how well our model will perform on data it hasn't seen before.

Model Fitting Exercise

  1. Partner up. On one computer:
    1. Write a function with the call signature predict_test_values(model, x_train, y_train, x_test) where model is a scikit learn model
      1. Fit the model on x_train and y_train
      2. Predict the y values for X_test
      3. Return a vector of predicted y values
    2. Write a second function with the call signature calc_train_and_test_error(model, x_train, y_train, x_test, y_test)
      1. Fit the model on x_train and y_train
      2. Predict the y values for x_test
      3. Predict the y values for x_train
      4. Calculate the mean_squared_error on both the train and test data.
      5. Return the train error and test error
    3. Describe to your partner the situations in which you might use each function

In [3]:
def mean_squared_error(y_true, y_pred):
    """
    calculate the mean_squared_error given a vector of true ys and a vector of predicted ys
    """
    diff = y_true - y_pred
    return np.dot(diff, diff) / len(diff)

def predict_test_values(model, X_train, y_train, X_test):
    model.fit(X_train, y_train)
    return model.predict(X_test)
    

def calc_train_and_test_error(model, X_train, y_train, X_test, y_test):
    model.fit(X_train, y_train)
    y_pred_train = model.predict(X_train)
    y_pred_test = model.predict(X_test)
    return mean_squared_error(y_train, y_pred_train), mean_squared_error(y_test, y_pred_test)

The Central Theses of Machine Learning

**1) A predictive model is only as good as its predictions on unseen data **

**2) Error on the dataset we trained on is not a good predictor of error on future data**

Why isn't error on the training data a good indicator of future performance? Overfitting.

Overfitting in One Picture


In [4]:
Image(url='http://radimrehurek.com/data_science_python/plot_bias_variance_examples_2.png')


Out[4]:

How to Fight Overfitting?

Ultimately we don't want to build a model which performs well on data we've already seen, we want to build a model which will perform well on data we haven't seen.

There are two linked strategies for to accomplish this: regularization and model selection.

Regularization

The idea in regularization is that we're going to modify our loss function to penalize it for being too complex. Simple models are better.

One way to do this is to try to keep our regression coefficients small. Why would we want to do this? One intuitive explanation is that if we have big regression coefficients we'll get large changes in the predicted values from small changes in input value. That's bad. Intuitively, our predictions should vary smoothly with the data.

So a model with smaller coefficients makes smoother predictions. It is simpler, which means it will have a harder time overfitting.

We can change our linear regression loss function to help us reduce overfitting:

Linear Regression Loss Function

\begin{eqnarray*} Loss(\beta) = MSE &=& \frac{1}{N} \sum_{i=1}^{N} (y_i - \hat y_i)^2 \\ &=& \frac{1}{N} \sum_{i=1}^{N} (y_i - x_i^T\beta)^2 \\ \end{eqnarray*}

L2 Regularized Linear Regression Loss Function -- "Ridge"

\begin{eqnarray*} Loss(\beta) &=& \frac{1}{N} \sum_{i=1}^{N} (y_i - x_i^T\beta)^2 + \alpha ||\beta||_2^2\\ &=& \frac{1}{N} \sum_{i=1}^{N} (y_i - x_i^T\beta)^2 + \alpha \beta^T \beta\\ &=& \frac{1}{N} \sum_{i=1}^{N} (y_i - x_i^T\beta)^2 + \alpha \sum_{d=1}^D \beta_d^2\\ \end{eqnarray*}

We won't get into details, but a ridge regression model can be optimized in much the same way as an unregularized linear regression: either with using some form of gradient descent or matrix-based solutions.


In [5]:
# Ridge Regression in scikit-learn
from sklearn import linear_model
model_ridge = linear_model.Ridge(alpha = .5)

# once it's been fit, you can look at the learned beta values of the model with: model_ridge.coef_

Ridge Regression Errors

  1. Partner up. On one computer:

    1. Using your calc_train_and_test_error function from the previous exercise:
      1. Calculate the training and testing error for a LinearRegression model on the dataset below
      2. Calculate the training and testing error for a Ridge regression model with alpha=1 on the dataset below
    2. Add up the absolute values of the coefficients of each model. Which is bigger?

      Note: If you have a fit model called m, then you can access a vector holding its learned coefficients with m.coef_.

      Note: Check out the functions np.sum() and np.abs()

    3. Discuss with your partner what's happening here


In [7]:
# load overfitting data
with np.load('data/overfitting_data.npz') as data:
    x_train = data['x_train']
    y_train = data['y_train']
    x_test = data['x_test']
    y_test = data['y_test']

model_lr = linear_model.LinearRegression()
model_ridge = linear_model.Ridge(alpha=1)

print "Linear Regression Training and Test Errors:"
print calc_train_and_test_error(model_lr, x_train, y_train, x_test, y_test)
print

print "Ridge Regression Training and Test Errors:"
print calc_train_and_test_error(model_ridge, x_train, y_train, x_test, y_test)
print

print "Sum of Linear Regression Coefficients:"
print np.sum(np.abs(model_lr.coef_))
print

print "Sum of Ridge Regression Coefficients:"
print np.sum(np.abs(model_ridge.coef_))
print


Linear Regression Training and Test Errors:
(2.4835421623898936e-05, 283.52728792173303)

Ridge Regression Training and Test Errors:
(0.018634112597991935, 9.5641560683733005)

Sum of Linear Regression Coefficients:
338.387469048

Sum of Ridge Regression Coefficients:
62.4912904062


In [8]:
?linear_model.Ridge

L1 Regularized Linear Regression Loss Function -- "LASSO"

LASSO is another regularization method. It penalizes not with the square of the regression coefficients (the $\beta$s) but with their absolute values.

LASSO has the additional property that it tends to push beta values of unimportant dimensions all the way to exactly 0. This has the beneficial property of enforcing sparsity in our model. If having lots of small coefficients leads to a simpler model, having lots of 0-valued coefficients lead to even simpler models.

\begin{eqnarray*} Loss(\beta) &=& \frac{1}{N} \sum_{i=1}^{N} (y_i - x_i^T\beta)^2 + \alpha ||\beta||_1\\ &=& \frac{1}{N} \sum_{i=1}^{N} (y_i - x_i^T\beta)^2 + \alpha \sum_{d=1}^D |\beta_d|\\ \end{eqnarray*}

In [9]:
# LASSO in scikit-learn
from sklearn import linear_model
model_lasso = linear_model.Lasso(alpha = 0.5)

LASSO Coefficients and Errors

  1. Partner up. On one computer:
    1. Using your calc_train_and_test_error again, calculate the training and testing error for a LASSO model with alpha=1 on the dataset from the previous exercise
    2. Add up the absolute values of the coefficients of the LASSO model. Compare it to the coefficient sums from the LinearRegression and Ridge models.
    3. Look at the first 10 coefficients of the LinearRegression, Ridge, and LASSO models.
    4. Discuss with your partner what's happening here

In [10]:
# Write your code here
model_lasso = linear_model.Lasso(alpha=1)

print "Ridge Regression Training and Test Errors:"
print calc_train_and_test_error(model_lasso, x_train, y_train, x_test, y_test)
print

print "Sum of Ridge Regression Coefficients:"
print np.sum(np.abs(model_lasso.coef_))
print


Ridge Regression Training and Test Errors:
(4.1142351854727695, 4.6028697944107124)

Sum of Ridge Regression Coefficients:
2.88729174216


In [11]:
n_disp_coefs = 10

print 'Linear Regression Coefficients:'
print model_lr.coef_[:n_disp_coefs]
print

print 'Ridge Regression Coefficients:'
print model_ridge.coef_[:n_disp_coefs]
print

print 'LASSO Coefficients:'
print model_lasso.coef_[:n_disp_coefs]
print


Linear Regression Coefficients:
[  5.22757470e-01   2.78289824e+00   4.04383818e+00   1.17544241e+00
   3.13230537e-01  -1.28127160e-01   5.11682173e-01   3.83754833e-03
  -1.19481096e+00   9.56448172e-01]

Ridge Regression Coefficients:
[ 1.01611626  1.77246927  3.06534773 -0.0333898   0.04378713  0.10472107
 -0.13445823  0.12656315  0.05779722  0.10204281]

LASSO Coefficients:
[ 0.03375129  0.92694409  1.92659636  0.          0.          0.         -0.
  0.          0.          0.        ]

L1 + L2 Regularized Linear Regression Loss Function -- "ElasticNet"

\begin{eqnarray*} Loss(\beta) &=& \frac{1}{2N} \sum_{i=1}^{N} (y_i - x_i^T\beta)^2 + \alpha \rho ||\beta||_1 + \frac{\alpha (1 - \rho)}{2} ||\beta||_2^2\\\\ &=& \frac{1}{2N} \sum_{i=1}^{N} (y_i - x_i^T\beta)^2 + \alpha \rho \sum_{d=1}^D |\beta_d| + \frac{\alpha (1 - \rho)}{2} \sum_{d=1}^D \beta_d^2\\ \end{eqnarray*}

In [12]:
from sklearn import linear_model
model_en = linear_model.ElasticNet(alpha=0.5, l1_ratio=0.1)

# note: scikit learn's current implementation of ElasticNet isn't stable with l1_ratio <= 0.01

ElasticNet Coefficients and Errors

  1. Partner up. On one computer:
    1. Using your calc_train_and_test_error again, calculate the training and testing error for an ElasticNet model with alpha=1 and l1_ratio=0.5 on the dataset from the previous exercises
    2. Add up the absolute values of the first 10 coefficients of the ElasticNet model. Compare it to the sums from the LinearRegression, Ridge, and LASSO models.
    3. Look at the first 10 coefficients of the ElasticNet model.
    4. Discuss with your partner what's happening here

In [13]:
# Write your code here

model_en = linear_model.ElasticNet(alpha=1, l1_ratio=0.5)

print 'ElasticNet Errors:'
print calc_train_and_test_error(model_en, x_train, y_train, x_test, y_test)
print 

print 'Sum of ElasticNet Coefficients'
print np.sum(np.abs(model_en.coef_))
print 

n_disp_coefs = 10

print 'ElasticNet Coefficients:'
print model_en.coef_[:n_disp_coefs]
print


ElasticNet Errors:
(4.2520891992612713, 4.7736076942707752)

Sum of ElasticNet Coefficients
2.92041057644

ElasticNet Coefficients:
[ 0.36672086  0.95411512  1.5995746   0.          0.          0.         -0.
  0.          0.          0.        ]

Cross Validation

Now we know three types of regularization for linear regression: ridge regression, LASSO, and elastic net.

All of our regularized models had better test error that simple linear regression. But how should we choose which model to ultimatley use or which parameters to use? The answer is through careful use of cross validation.

There are many forms of cross validation, but the basic idea of each is to train your model on some data and estimate it's future performance on other data.

Types of Cross Validation

Validation Set Cross Validation

  1. Pick an amount of training data to be in your validation data set (e.g. 10%)
  2. Randomly split datapoints into training points (90%) and validation points (10%)
  3. Train your model on the training data
  4. Test your model on the validation data, record the validation error
  5. Estimated future errors is the validation error
  • Good: Easy and computationally cheap
  • Bad: Statistically noisy and wastes data

Aside: So far we've been calculating error on out test dataset. This is conceptually almost identical to using a validation set, but with two significant differences:

  1. We don't have to peek at our test data set. This is good because if we do that too much, we can actually still overfit to our test data and still perform poorly on future unseen data.
  2. We don't have to be given the $\mathbf{y}$ vector for our test dataset. Validation set cross validation only requires a training dataset.

In [14]:
# a helper function for performing validation set cross validation
from sklearn.cross_validation import train_test_split
validation_portion = 0.1
seed = 1234
x_train_small, x_valid, y_train_small, y_valid = \
    train_test_split(x_train, y_train, test_size=validation_portion, random_state=seed)

print 'Original Training Set Size:'
print x_train.shape, y_train.shape
print

print 'Reducted Training Set Size:'
print x_train_small.shape, y_train_small.shape
print

print 'Validation Set Size:'
print x_valid.shape, y_valid.shape
print


Original Training Set Size:
(600, 598) (600,)

Reducted Training Set Size:
(540, 598) (540,)

Validation Set Size:
(60, 598) (60,)

Validation Set Cross Validation Exercise

  1. Partner up. On one computer:
    1. Write a function with the call signature validation_set_error(model, x_train, y_train, validation_portion=0.1, seed=1234) which returns the validation set estimate of the future error for the given model. This function should:
      1. Split the data into a reduced training set and a validation set
      2. Train on the reduced training set
      3. Estimate the mean squared error on the validation set
      4. Return that estimate
    2. Use your calc_train_and_test_error(model, x_train, y_train, x_test, y_test) function to calculate training and test set errors for these
    3. Use this your validation_set_error function to estimate the future error on the overfitting data for:
      1. A linear regression model
      2. A ridge regression models with alpha = 10
    4. Do this for multiple random seeds
    5. Does validation error do a good job of predicting test error?
    6. If you have time: How does changing the validation_portion affect the similarity between the validation and test error?

In [19]:
def validation_set_error(model, x_train, y_train, validation_portion=0.1, seed=1234):
    # FILL IN YOUR CODE HERE

    x_train_small, x_valid, y_train_small, y_valid = \
        train_test_split(x_train, y_train, test_size=validation_portion, random_state=seed)
    model.fit(x_train_small, y_train_small)
    y_pred_valid = model.predict(x_valid)
    return mean_squared_error(y_valid, y_pred_valid)
      
    
# set up models
model_lr_valid = linear_model.LinearRegression()
model_ridge_valid = linear_model.Ridge(alpha=10)

# calculate errors
valid_portion = .1
n_seeds = 5
print "Linear Regression Training and Test Errors:"
# FILL IN YOUR CODE HERE
print calc_train_and_test_error(model_lr_valid, x_train_small, y_train_small, x_test, y_test)

print
print "Linear Regression Validation Errors:"
# FILL IN YOUR CODE HERE
print validation_set_error(model_lr_valid, x_train, y_train, validation_portion=0.1, seed=1234)
print 

for seed in range(n_seeds):
    print validation_set_error(model_lr_valid, x_train, y_train, validation_portion=valid_portion, seed=seed)
    print

print "Ridge Regression Training and Test Errors:"
# FILL IN YOUR CODE HERE
print calc_train_and_test_error(model_ridge_valid, x_train_small, y_train_small, x_test, y_test)


print
print "Ridge Regression Validation Errors:"
# FILL IN YOUR CODE HERE
print validation_set_error(model_ridge_valid, x_train, y_train, validation_portion=0.1, seed=1234)
print 

for seed in range(n_seeds):
    print validation_set_error(model_ridge_valid, x_train, y_train, validation_portion=valid_portion, seed=seed)
    print


Linear Regression Training and Test Errors:
(2.2467754393471771e-28, 8.0788753125188482)

Linear Regression Validation Errors:
9.00825907283

9.50207421262

11.6967800266

8.55732897985

9.12801394143

7.60975925351

Ridge Regression Training and Test Errors:
(0.037116269305342071, 4.8163269566646836)

Ridge Regression Validation Errors:
4.44120540399

3.61817500364

7.12476980873

5.32580668571

5.74292650031

4.6239411424

K-Fold Cross Validation

K-Fold cross validation is another cross validation method for estimating the out-of-sample error of a model. It works like this:

  1. Partition the training data into K folds
  2. For each fold k in 1 to K:
    1. Train the model on all your data except the data in fold k
    2. Record the error on the the data in fold k
  3. Estimate future error as average error across all folds

In [20]:
Image(url='https://chrisjmccormick.files.wordpress.com/2013/07/10_fold_cv.png')


Out[20]:
  • Good: Only wastes 100/k% of the data at a time
  • Bad: Takes k times long as just training one model, still wastes 100/k% of the data

In [21]:
# scikit learn provides a useful object to help you perform kfold cross validation
from sklearn.cross_validation import KFold

n_data = len(y_train)
fold_count = 0
for train_reduced_row_ids, valid_row_ids in KFold(n_data, n_folds=4):
    print
    print 
    print "FOLD %d:" % fold_count
    print "-------"
    print("train_ids:\n%s\n\nvalid_ids\n%s" % (train_reduced_row_ids, valid_row_ids))
    x_train_reduced = x_train[train_reduced_row_ids]
    y_train_reduced = y_train[train_reduced_row_ids]
    x_valid = x_train[valid_row_ids]
    y_valid = y_train[valid_row_ids]
    fold_count += 1



FOLD 0:
-------
train_ids:
[150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599]

valid_ids
[  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35
  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53
  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71
  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89
  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107
 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
 144 145 146 147 148 149]


FOLD 1:
-------
train_ids:
[  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35
  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53
  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71
  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89
  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107
 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
 144 145 146 147 148 149 300 301 302 303 304 305 306 307 308 309 310 311
 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599]

valid_ids
[150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
 294 295 296 297 298 299]


FOLD 2:
-------
train_ids:
[  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35
  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53
  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71
  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89
  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107
 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
 288 289 290 291 292 293 294 295 296 297 298 299 450 451 452 453 454 455
 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599]

valid_ids
[300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
 444 445 446 447 448 449]


FOLD 3:
-------
train_ids:
[  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35
  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53
  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71
  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89
  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107
 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449]

valid_ids
[450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
 594 595 596 597 598 599]

In [22]:
# NOTE: KFolds isn't random at all.  It's important to shuffle your data first before using it. 
from sklearn.utils import shuffle
x_train_shuffled, y_train_shuffled = shuffle(x_train, y_train)

K-Fold Cross Validation Exercise

  1. Partner up. On one computer:
    1. Write a function with the call signature kfold_error(model, x_train, y_train, k=4, seed=1234) which returns the k-fold cross validation estimate of the future error for the given model. This function should:
      1. Shuffle the training data set (both $\mathbf{x}$ and $\mathbf{y}$ in unison)
      2. For each fold:
        1. Split the data into a reduced training set and a validation set
        2. Train on the reduced training set
        3. Estimate the mean squared error on the validation set
        4. Add the estimated error to a running sum of the estimated total error
      3. Return the average error across folds: i.e.: the estimated total error divided by the number of folds
    2. Use your calc_train_and_test_error(model, x_train, y_train, x_test, y_test) function to calculate training and test set errors for these
    3. Use your kfold_error function with k=5 to estimate the future error on the overfitting data for:
      1. A linear regression model
      2. A ridge regression models with alpha = 10
    4. Do this for multiple random seeds
    5. Does k-fold error do a good job of predicting test error?

In [30]:
def kfold_error(model, x_train, y_train, k=4, seed=1234):
    # FILL IN YOUR CODE HERE
    
    # shuffle training data
    x_train_shuffled, y_train_shuffled = shuffle(x_train, y_train, random_state=seed)
    
    n_data = len(y_train)
    error_sum = 0
    for train_reduced_row_ids, valid_row_ids in KFold(n_data, n_folds=k):
        x_train_reduced = x_train_shuffled[train_reduced_row_ids]
        y_train_reduced = y_train_shuffled[train_reduced_row_ids]
        x_valid = x_train_shuffled[valid_row_ids]
        y_valid = y_train_shuffled[valid_row_ids]
        model.fit(x_train_reduced, y_train_reduced)
        y_valid_pred = model.predict(x_valid)
        error_sum += mean_squared_error(y_valid, y_valid_pred)
    return error_sum*1.0 / k
    

# set up models
model_lr_valid = linear_model.LinearRegression()
model_ridge_valid = linear_model.Ridge(alpha=10)

# calculate errors
n_seeds = 3
k = 5

print "Linear Regression Training and Test Errors:"
# FILL IN YOUR CODE HERE
print calc_train_and_test_error(model_lr_valid, x_train, y_train, x_test, y_test)

print
print "Linear Regression K-Fold Errors:"
# FILL IN YOUR CODE HERE
print 
for seed in range(n_seeds):
    print kfold_error(model_lr_valid, x_train, y_train, k=k, seed=seed)
    print 

print
print "Ridge Regression Training and Test Errors:"
# FILL IN YOUR CODE HERE
print calc_train_and_test_error(model_ridge_valid, x_train, y_train, x_test, y_test)


print
print "Ridge Regression K-Fold Errors:"
# FILL IN YOUR CODE HERE
print 
for seed in range(n_seeds):
    print kfold_error(model_ridge_valid, x_train, y_train, k=k, seed=seed)
    print


Linear Regression Training and Test Errors:
(2.4835421623898936e-05, 283.52728792173303)

Linear Regression K-Fold Errors:

7.03764511003

7.00059269572

6.6986525009


Ridge Regression Training and Test Errors:
(0.064063243432623679, 4.9205415455726902)

Ridge Regression K-Fold Errors:

5.77769677178

5.78170553945

5.6587338965

Putting It All Together: Model and Hyperparameter Selection with Cross Validation

  1. For each model and hyperparameter combo you're willing to consider:
    1. Estimate the model's performance on future data using cross validation
  2. Pick the model with the best estimated future performance
  3. Train the best model from scratch on the full dataset. This is your final model

In [32]:
[np.nan] + [1,2]


Out[32]:
[nan, 1, 2]

In [33]:
def model_name(model):
    s = model.__str__().lower()
    if "linearregression" in s:
        return 'LinearRegression'
    elif "lasso" in s:
        return 'Lasso(a=%g)' % model.alpha
    elif "ridge" in s:
        return 'Ridge(a=%g)' % model.alpha
    elif "elastic" in s:
        return 'ElasticNet(a=%g, r=%g)' % (model.alpha, model.l1_ratio)
    else:
        raise ValueError("Unknown Model Type")

def create_models(alphas=(.01, .03, .1, .3, 1, 3), l1_ratios=(.7, .5, .3)):
    models = [linear_model.LinearRegression()]
    models.extend([linear_model.Ridge(a) for a in alphas])
    models.extend([linear_model.Lasso(a) for a in alphas])
    models.extend([linear_model.ElasticNet(a, l1_ratio=l) for a in alphas for l in l1_ratios])
    return models

def results_df(models, betas_true, x_train, y_train, x_test, y_test, k=4):
    n_data, n_dim = x_train.shape

    n_zeros = n_dim - len(betas_true)
    
    betas_true = np.concatenate([betas_true, np.zeros(n_zeros)])
    
    # fit models to training data
    [m.fit(x_train, y_train) for m in models]
    
    betas = np.vstack([betas_true] + [m.coef_ for m in models])
    beta_names = ['Beta ' + str(i) for i in range(n_dim)]

    # set up model names
    model_names =  ["True Coefs"] + [model_name(m) for m in models]
    df = pd.DataFrame(data=betas, columns=beta_names, index=model_names)

    # calculate training errors
    y_preds = [m.predict(x_train) for m in models]
    errors = [np.nan] + [mean_squared_error(y_train, y_pred) for y_pred in y_preds]
    df['Train Error'] = errors

    # calculate validation errors
    errors = [np.nan] + [kfold_error(m, x_train, y_train, k=k) for m in models]
    df['Cross Validation Error'] = errors

    # calculate test errors
    y_preds = [m.predict(x_test) for m in models]
    errors = [np.nan] + [mean_squared_error(y_test, y_pred) for y_pred in y_preds]
    df['Test Error'] = errors

    return df


# these are some of the magic parameters that I used to actually 
# generate the overfitting dataset
n_dim = 598
n_dim_meaningful = 3
n_dim_disp_extra = 2

# the actual betas used to generate the y values.  the rest were 0.
betas_true = np.arange(n_dim_meaningful) + 1

# create a whole bunch of untrained models
models = create_models(alphas=(.01, .03, .1, .3, 1), l1_ratios=(.9, .7, .5))

# 
all_results = results_df(models, betas_true, x_train, y_train, x_test, y_test, k=4)

# decide which columns we want to display
disp_cols = ["Beta " + str(i) for i in range(n_dim_meaningful + n_dim_disp_extra)] 
disp_cols += ['Train Error', 'Cross Validation Error', 'Test Error']

# display the results
all_results[disp_cols]


Out[33]:
Beta 0 Beta 1 Beta 2 Beta 3 Beta 4 Train Error Cross Validation Error Test Error
True Coefs 1.000000 2.000000 3.000000 0.000000 0.000000 NaN NaN NaN
LinearRegression 0.522757 2.782898 4.043838 1.175442 0.313231 0.000025 7.042731 9.159262
Ridge(a=0.01) 0.867059 2.290546 3.729941 0.570987 0.380292 0.001033 6.590630 8.592261
Ridge(a=0.03) 1.028546 2.023949 3.548358 0.237767 0.370161 0.002749 6.588766 8.590441
Ridge(a=0.1) 1.088696 1.847044 3.386562 0.012841 0.272410 0.005693 6.582288 8.584100
Ridge(a=0.3) 1.065763 1.788885 3.247394 -0.050784 0.142292 0.010186 6.564170 8.566235
Ridge(a=1) 1.016116 1.772469 3.065348 -0.033390 0.043787 0.018634 6.504991 8.506474
Lasso(a=0.01) 1.076240 1.956283 2.955116 0.000000 0.025530 0.213388 1.701747 1.849997
Lasso(a=0.03) 1.042435 1.941418 2.952131 0.000000 0.002460 0.526780 1.223279 1.196381
Lasso(a=0.1) 0.972258 1.869852 2.892761 -0.000000 0.000000 0.968836 1.024546 0.895046
Lasso(a=0.3) 0.764523 1.659750 2.677197 0.000000 0.000000 1.235803 1.264843 1.120443
Lasso(a=1) 0.033751 0.926944 1.926596 0.000000 0.000000 4.114235 4.166927 4.301203
ElasticNet(a=0.01, r=0.9) 1.073393 1.951365 2.947436 0.000000 0.027348 0.195976 1.760720 1.935114
ElasticNet(a=0.01, r=0.7) 1.066012 1.936668 2.931448 0.000000 0.031150 0.163034 1.919308 2.167257
ElasticNet(a=0.01, r=0.5) 1.046440 1.907626 2.908069 0.000000 0.029275 0.127897 2.191965 2.583608
ElasticNet(a=0.03, r=0.9) 1.042974 1.931661 2.936235 0.000000 0.008043 0.484044 1.261913 1.240859
ElasticNet(a=0.03, r=0.7) 1.038972 1.908386 2.901951 0.000000 0.014723 0.401288 1.361827 1.360261
ElasticNet(a=0.03, r=0.5) 1.026654 1.885132 2.862618 0.000000 0.020993 0.316085 1.547012 1.592804
ElasticNet(a=0.1, r=0.9) 0.971808 1.860572 2.872529 -0.000000 0.000000 0.960364 1.041134 0.906070
ElasticNet(a=0.1, r=0.7) 0.968971 1.841385 2.828162 -0.000000 0.000000 0.913444 1.092529 0.967566
ElasticNet(a=0.1, r=0.5) 0.961790 1.813670 2.765941 0.000000 0.000000 0.807426 1.215067 1.092389
ElasticNet(a=0.3, r=0.9) 0.771897 1.639918 2.624446 0.000000 0.000000 1.277930 1.307354 1.168137
ElasticNet(a=0.3, r=0.7) 0.785336 1.603633 2.528307 0.000000 0.000000 1.370249 1.400441 1.273228
ElasticNet(a=0.3, r=0.5) 0.797276 1.571245 2.442910 0.000000 0.000000 1.469114 1.512212 1.390285
ElasticNet(a=1, r=0.9) 0.125708 0.934637 1.835475 0.000000 0.000000 4.112881 4.189787 4.313581
ElasticNet(a=1, r=0.7) 0.265489 0.946058 1.698143 0.000000 0.000000 4.168660 4.233218 4.410287
ElasticNet(a=1, r=0.5) 0.366721 0.954115 1.599575 0.000000 0.000000 4.252089 4.309107 4.534828

In [35]:
%matplotlib inline
import matplotlib.pyplot as plt
f = plt.figure()
plt.scatter(all_results['Cross Validation Error'], all_results['Test Error'])
plt.xlabel('Cross Validation Error')
plt.ylabel('Test Error')
f.set_size_inches(8, 8)
plt.show()



In [36]:
# scikit learn includes some functions for making cross validation easier 
# and computationally faster for a some models
from sklearn import linear_model
model_ridge_cv = linear_model.RidgeCV(alphas=[0.1, 1.0, 10.0])
model_lasso_cv = linear_model.LassoCV(alphas=[0.1, 1.0, 10.0])
model_en_cv = linear_model.ElasticNetCV(l1_ratio=[.9], n_alphas=100)

Caveats:

  • You can still overfit with intensive cross validation based model selection!
  • But it's much better than without

Summary:

  • The Central Theses of Machine Learning:
    • We're only interested in predictive performance on unseen data, not on seen data.
    • Training error estimates error on seen data
    • Cross validation error estimates error on unseen data
  • Regularization strategies change how to train a model so that it will perform better on unseen data
  • We talked about three forms of regularization for linear regression:
    • Ridge Regression (L2 Penalty)
    • LASSO (L1 Penalty)
    • ElasticNet (L1 + L2 Penalties)
  • We talked about two kinds of cross validation error:
    • Validation Error -- split your training set into a reduced training set and a validation set
    • K-Fold Error -- Split your training data into k reduced training sets and a validation sets
  • Regularization introduces new hyperparameters
  • Use a cross validated estimate of future performance to choose your model and hyperparameter settings